package com.igeek.dao;

import com.igeek.domain.Product;
import com.igeek.utils.JDBCTools;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author jerryHe
 * @create 2019-10-09 16:18
 */
public class ProductDao {
    QueryRunner qr = new QueryRunner(JDBCTools.getDataSource());
    String sql = "";

    public List<Product> findData(int nowPage, int i,String cid) {
        sql="select * from product where cid = ? limit ?,?";
        int offset = (nowPage-1)*i;
        try {
            return qr.query(sql,new BeanListHandler<>(Product.class),cid,offset,i);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;

    }

    public List<Product> findProductsByCid(String cid) {
        sql = "select * from product where cid = ?";
        try {
            return qr.query(sql,new BeanListHandler<>(Product.class),cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int getCount(String cid) {
        sql ="select count(*) from product where cid= ?";
        Long result = 0L;
        try {
            result = qr.query(sql,new ScalarHandler<Long>(),cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Integer.parseInt(result+"");
    }

    public List<Product> getHotProducts() {
        sql="select * from product where is_hot = 1 limit 0,9";
        try {
            return qr.query(sql,new BeanListHandler<>(Product.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Product> getNewProducts() {
        sql="select * from product order by pdate desc limit 0,9";
        try {
            return qr.query(sql,new BeanListHandler<>(Product.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Product getProductByPid(String pid) {
        sql = "select * from product p ,category c where pid = ? and c.cid = p.cid";
        try {
            return  qr.query(sql,new BeanHandler<>(Product.class),pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
